/*
 * Copyright (c) Modify by T C L on 2019.2.27.
 */

package com.egg.ylt.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.MyPayResult;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.pojo.PayTypeEntity;
import com.egg.ylt.pojo.WeChatPayEntity;
import com.egg.ylt.presenter.ICardPayPresenter;
import com.egg.ylt.presenter.impl.CardPayPresenterImpl;
import com.egg.ylt.view.ICardPayView;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.ToastUtil;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_Payment extends BaseActivity<CardPayPresenterImpl> implements ICardPayView {

    @BindView(R.id.include_rl_view)
    RelativeLayout mIncludeRlView;
    @BindView(R.id.include_tv_title)
    TextView includeTvTitle;
    @BindView(R.id.loading_view_ll)
    LinearLayout mLoadingViewLl;
    @BindView(R.id.meal_card_name_tv)
    TextView mMealCardNameTv;
    @BindView(R.id.iv_selector_wx)
    ImageView mWxSelectorIv;
    @BindView(R.id.iv_selector_zfb)
    ImageView mZfbSelectorIv;
    @BindView(R.id.money_need_pay_tv)
    TextView mMoneyNeedPayTv;
    @BindView(R.id.pay_immediate_tv)
    TextView mPayImmediateTv;
    /**
     * 支付宝支付渠道
     */
    private static final int SDK_PAY_FLAG = 1;
    /**
     * 微信支付渠道
     */
    private String mPayType = ICardPayPresenter.PAY_TYPE_ALIPAY;//支付方式 0 微信，1支付宝
    private IWXAPI msgApi;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    MyPayResult payResult = new MyPayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //支付成功，去我的次卡界面
                        ToastUtil.makeText(mContext, "支付成功", false);
                        readyGoThenKill(ACT_UserTimeCard.class);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //支付失败
                        ToastUtil.makeText(mContext, "支付失败,请重新支付", false);
                    }
                    break;

                }
            }
        }
    };
    private String mPayPrice;
    private String mCardName;
    private String mCardId;
    private String mTicketAmount;
    private String mTicketId;
    private String mId;

    @Override
    protected void getBundleExtras(Bundle extras) {
        mId = extras.getString("id");
        mCardId = extras.getString("cardId");
        mCardName = extras.getString("cardName");
        mPayPrice = extras.getString("price");
        mTicketId = extras.getString("ticketId");
        mTicketAmount = extras.getString("ticketAmount");
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_pay_ment;
    }

    @Override
    protected View getLoadingTargetView() {
        return mLoadingViewLl;
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setStatusBarColor(this, R.color.ylt_whit);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, mIncludeRlView);

        //设置title 和 套餐卡数据
        includeTvTitle.setText("支付");

        mMealCardNameTv.setText(mCardName);
        mMoneyNeedPayTv.setText("¥" + mPayPrice);
        mPayImmediateTv.setText("立即支付 ¥" + mPayPrice);

        // 将该app注册到微信
        msgApi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
        msgApi.registerApp(Constants.WX_APP_ID);
        //默认支付宝支付
        mZfbSelectorIv.setSelected(true);

//        mPresenter.getPayType(Constants.TOKEN, mCardId, Constants.COMPANYID);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @OnClick({R.id.include_iv_back, R.id.wx_ll, R.id.zfb_ll, R.id.pay_immediate_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.include_iv_back://返回键
                finish();
                break;
            case R.id.wx_ll://微信
                mPayType = ICardPayPresenter.PAY_TYPE_WE_CHAT;
                mWxSelectorIv.setSelected(true);
                mZfbSelectorIv.setSelected(false);
                break;
            case R.id.zfb_ll://支付宝
                mPayType = ICardPayPresenter.PAY_TYPE_ALIPAY;
                mWxSelectorIv.setSelected(false);
                mZfbSelectorIv.setSelected(true);
                break;
            case R.id.pay_immediate_tv://支付按钮
                if (StringUtil.isEmpty(mPayType)) {
                    ToastUtil.makeText(mContext, "请选择支付方式", false);
                    return;
                }
                if (ICardPayPresenter.PAY_TYPE_WE_CHAT.equals(mPayType)) {
                    //请求微信支付订单信息
                    mPresenter.getWXOrderInfo(Constants.TOKEN, Constants.COMPANYID, mPayType, mCardId,
                            mCardName, mPayPrice, mId, mTicketId, mTicketAmount);
                } else if (ICardPayPresenter.PAY_TYPE_ALIPAY.equals(mPayType)) {
                    //请求支付宝支付订单信息
                    mPresenter.getAlipayOrderInfo(Constants.TOKEN, Constants.COMPANYID, mPayType, mCardId,
                            mCardName, mPayPrice, mId, mTicketId, mTicketAmount);
                }
                break;
        }
    }


    @Override
    public void resolveAlipayOrder(final String orderInfo) {
        if (StringUtil.isEmpty(orderInfo)) {
            return;
        }

        //去调用支付宝支付
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(mContext);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @Override
    public void resolveWxOrder(String orderInfo) {
        //微信支付订单信息
        WeChatPayEntity entity = new Gson().fromJson(orderInfo, WeChatPayEntity.class);
        Constants.WX_PAY_TYPE = Constants.WX_PAY_CARD;
        PayReq request = new PayReq();
        //微信开放平台审核通过的应用APPID
        request.appId = Constants.WX_APP_ID;
        //微信支付分配的商户号
        request.partnerId = entity.getPartnerid();
        //微信返回的支付交易会话ID
        request.prepayId = entity.getPrepayid();
        //暂填写固定值Sign=WXPay
        request.packageValue = "Sign=WXPay";
        //随机字符串，不长于32位。推荐随机数生成算法
        request.nonceStr = entity.getNoncestr();
        //时间戳
        request.timeStamp = entity.getTimestamp();
        //签名
        request.sign = entity.getSign();
//        Log.e("PayActivity", request.checkArgs()+"");//这是检查你请求参数是否有误，如果打印是false，请检查你的请求参数是否是上面的几个
//        Log.e("PayActivity",msgApi.sendReq(request)+""); //这表示能够调起api，一般上面那个成功，这个没有问题。两个Log如果打印都是true，恭喜你离成功不远了
//        ToastUtil.makeText(mContext, "正常调起支付", false);
        msgApi.sendReq(request);
//        finish();
//        Log.e("PayActivity", request.checkArgs()+"");
    }

    @Override
    public void getPayData(PayTypeEntity entity) {
        if (entity == null) {
            return;
        }
        //套餐卡name
        mCardName = entity.getCardName();
        mMealCardNameTv.setText(entity.getCardName());
    }


}
